package com.sy.nio.c1;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.sy.nio.c1.ByteBufferUtil.debugAll;

/**
 * @Author yumax
 * @Date 2024 01 04 09 44
 **/
@Slf4j
public class Server2 {

    public static void main(String[] args) throws IOException {
        //使用nio来理解阻塞模式
        //1. 创建服务器
        final ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);//设置非阻塞模式
        //2. 绑定监听端口
        ssc.bind(new InetSocketAddress(8989));
        ByteBuffer buffer = ByteBuffer.allocate(16);
        //3. 连接集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            //4. accept 建立与客户端连接，SocketChannel用来与客户端之间通信
            //log.debug("connecting...");
            final SocketChannel channel = ssc.accept(); //阻塞方法，线程停止运行；非阻塞，没有连接返回null

            if (channel != null) {
                log.debug("connected ...{}", channel);
                channel.configureBlocking(false);//非阻塞模式
                channels.add(channel);
            }

            for (SocketChannel item : channels) {
                final int read = item.read(buffer);//（客户端没有发送数据）会阻塞方法，线程停止;非阻塞模式，会继续运行
                if (read > 0) {
                    buffer.flip();
                    debugAll(buffer);
                    buffer.clear();
                    log.debug("after read {}",item);
                }
            }
        }

    }
}
